package com.ren.frame;

import com.ren.constants.AppConstants;
import com.ren.service.ScheduleManage;
import com.ren.service.DataAdapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 主框架窗口类，用于显示四象限时间管理界面
 * 提供任务编辑、窗口固定、数据保存等功能
 */
public class MainFrame extends JFrame {

    private static final Logger log = LoggerFactory.getLogger(MainFrame.class);
    private ScheduleManage scheduleManage;
    private DataAdapter dataAdapter;
    private boolean isPinned = false;
    private Point originalLocation = null; // 记录窗口原始位置

    // 四个象限的文本区域
    private MarkdownEditorPane importantUrgentArea;
    private MarkdownEditorPane importantNotUrgentArea;
    private MarkdownEditorPane notImportantUrgentArea;
    private MarkdownEditorPane notImportantNotUrgentArea;

    /**
     * 构造函数，初始化主窗口及所有组件
     */
    public MainFrame() {
        scheduleManage = new ScheduleManage();
        dataAdapter = new DataAdapter();

        initializeComponents();
        setupLayout();
        loadAllContent();
        setupEventListeners();
        addWindowMouseListener();

        setTitle(AppConstants.APP_TITLE);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 500);
        setLocationRelativeTo(null);
    }

    // ==================== 初始化相关方法 ====================

    /**
     * 初始化所有文本区域组件
     */
    private void initializeComponents() {
        // 初始化 MarkdownEditorPane 文本区域
        importantUrgentArea = new MarkdownEditorPane(AppConstants.CATEGORY_IMPORTANT_URGENT);
        importantNotUrgentArea = new MarkdownEditorPane(AppConstants.CATEGORY_IMPORTANT_NOT_URGENT);
        notImportantUrgentArea = new MarkdownEditorPane(AppConstants.CATEGORY_NOT_IMPORTANT_URGENT);
        notImportantNotUrgentArea = new MarkdownEditorPane(AppConstants.CATEGORY_NOT_IMPORTANT_NOT_URGENT);

        // 初始化预览面板
        MarkdownPreviewPanel importantUrgentPreview = new MarkdownPreviewPanel();
        MarkdownPreviewPanel importantNotUrgentPreview = new MarkdownPreviewPanel();
        MarkdownPreviewPanel notImportantUrgentPreview = new MarkdownPreviewPanel();
        MarkdownPreviewPanel notImportantNotUrgentPreview = new MarkdownPreviewPanel();

        // 设置关联关系
        importantUrgentArea.setPreviewPanel(importantUrgentPreview);
        importantNotUrgentArea.setPreviewPanel(importantNotUrgentPreview);
        notImportantUrgentArea.setPreviewPanel(notImportantUrgentPreview);
        notImportantNotUrgentArea.setPreviewPanel(notImportantNotUrgentPreview);

        // 设置文本区域属性
        setupTextArea(importantUrgentArea);
        setupTextArea(importantNotUrgentArea);
        setupTextArea(notImportantUrgentArea);
        setupTextArea(notImportantNotUrgentArea);

        // 创建设置菜单
        createMenu();
    }

    /**
     * 设置文本区域的基本样式和属性
     * @param textPane 需要设置的文本区域
     */
    private void setupTextArea(MarkdownEditorPane textPane) {
        textPane.setFont(AppConstants.DEFAULT_FONT);
        textPane.setEditable(false);
        textPane.setBackground(Color.WHITE);
    }

    /**
     * 设置主窗口布局，创建四个象限面板并添加到主窗口
     */
    private void setupLayout() {
        setLayout(new GridLayout(2, 2, 5, 5));

        // 创建带标题的面板
        JPanel importantUrgentPanel = createTitledPanel(AppConstants.QUADRANT_IMPORTANT_URGENT, new JScrollPane(importantUrgentArea));
        JPanel importantNotUrgentPanel = createTitledPanel(AppConstants.QUADRANT_IMPORTANT_NOT_URGENT, new JScrollPane(importantNotUrgentArea));
        JPanel notImportantUrgentPanel = createTitledPanel(AppConstants.QUADRANT_NOT_IMPORTANT_URGENT, new JScrollPane(notImportantUrgentArea));
        JPanel notImportantNotUrgentPanel = createTitledPanel(AppConstants.QUADRANT_NOT_IMPORTANT_NOT_URGENT, new JScrollPane(notImportantNotUrgentArea));

        // 添加到主窗口
        add(importantUrgentPanel);
        add(importantNotUrgentPanel);
        add(notImportantUrgentPanel);
        add(notImportantNotUrgentPanel);
    }

    /**
     * 创建带标题边框的面板
     * @param title 面板标题
     * @param scrollPane 滚动面板
     * @return 带标题的面板
     */
    private JPanel createTitledPanel(String title, JScrollPane scrollPane) {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder(title));
        panel.add(scrollPane, BorderLayout.CENTER);

        // 设置工具提示（鼠标悬浮时显示介绍信息）
        String introduction = getIntroductionForTitle(title);
        if (introduction != null && !introduction.isEmpty()) {
            // 使用HTML格式化文本，设置宽度限制
            panel.setToolTipText("<html><p width=\"300\">" + introduction + "</p></html>");
        }

        return panel;
    }

    /**
     * 根据标题获取对应的介绍信息
     * @param title 面板标题
     * @return 介绍信息
     */
    private String getIntroductionForTitle(String title) {
        if (AppConstants.QUADRANT_IMPORTANT_URGENT.equals(title)) {
            return AppConstants.I_U_INTRODUCE;
        } else if (AppConstants.QUADRANT_IMPORTANT_NOT_URGENT.equals(title)) {
            return AppConstants.I_NU_INTRODUCE;
        } else if (AppConstants.QUADRANT_NOT_IMPORTANT_URGENT.equals(title)) {
            return AppConstants.NI_U_INTRODUCE;
        } else if (AppConstants.QUADRANT_NOT_IMPORTANT_NOT_URGENT.equals(title)) {
            return AppConstants.NI_NU_INTRODUCE;
        }
        return "";
    }

    // ==================== 菜单相关方法 ====================

    /**
     * 创建设置菜单
     */
    private void createMenu() {
        JMenuBar menuBar = new JMenuBar();

        // 创建一个面板来更好地控制布局
        JPanel menuPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        menuPanel.setOpaque(false);

        // 固定功能菜单项
        JMenuItem pinMenuItem = new JMenuItem(AppConstants.FIXED_WINDOW);
        pinMenuItem.setName("pinMenuItem");
        pinMenuItem.addActionListener(e -> togglePinWindow());
        menuPanel.add(pinMenuItem);

        // 使命宣言菜单项
        JMenuItem missionStatementItem = new JMenuItem(AppConstants.MISSION_STATEMENT);
        missionStatementItem.addActionListener(e -> showMissionStatementDialog());
        menuPanel.add(missionStatementItem);


        // 设置功能菜单项
        JMenuItem settingsItem = new JMenuItem(AppConstants.SETTING);
        settingsItem.addActionListener(e -> {
            SettingsFrame settingsFrame = new SettingsFrame(this);
            settingsFrame.setVisible(true);
        });
        menuPanel.add(settingsItem);

        // 将面板添加到菜单栏
        menuBar.add(menuPanel);
        setJMenuBar(menuBar);
    }

    /**
     * 切换窗口固定状态
     * 固定时禁止调整大小和移动窗口，取消固定时恢复
     */
    private void togglePinWindow() {
        isPinned = !isPinned;

        if (isPinned) {
            // 固定窗口：禁止调整大小和移动
            setResizable(false);
            // 记录当前位置
            originalLocation = getLocation();
            // 添加组件监听器防止窗口移动
            addComponentListener(new ComponentAdapter() {
                @Override
                public void componentMoved(ComponentEvent e) {
                    // 强制窗口回到原始位置
                    if (originalLocation != null) {
                        setLocation(originalLocation);
                    }
                }
            });
        } else {
            // 取消固定
            setResizable(true);
            // 移除位置锁定监听器
            ComponentListener[] listeners = getComponentListeners();
            for (ComponentListener listener : listeners) {
                if (listener instanceof ComponentAdapter) {
                    removeComponentListener(listener);
                }
            }
            originalLocation = null;
        }

        updatePinMenuItemText();
    }

    /**
     * 更新固定菜单项的显示文本
     */
    private void updatePinMenuItemText() {
        JMenuBar menuBar = getJMenuBar();
        if (menuBar != null && menuBar.getComponentCount() > 0) {
            Component menuPanel = menuBar.getComponent(0);
            if (menuPanel instanceof JPanel) {
                Component[] components = ((JPanel) menuPanel).getComponents();
                for (Component component : components) {
                    if (component instanceof JMenuItem && "pinMenuItem".equals(((JMenuItem) component).getName())) {
                        JMenuItem pinMenuItem = (JMenuItem) component;
                        pinMenuItem.setText(isPinned ? AppConstants.WINDOW_FIXED : AppConstants.FIXED_WINDOW);
                        break;
                    }
                }
            }
        }
    }

    // ==================== 事件监听相关方法 ====================

    /**
     * 设置各种事件监听器，包括双击编辑和焦点丢失保存
     */
    private void setupEventListeners() {
        // 为每个文本区域添加双击编辑功能
        addDoubleClickEdit(importantUrgentArea, AppConstants.CATEGORY_IMPORTANT_URGENT);
        addDoubleClickEdit(importantNotUrgentArea, AppConstants.CATEGORY_IMPORTANT_NOT_URGENT);
        addDoubleClickEdit(notImportantUrgentArea, AppConstants.CATEGORY_NOT_IMPORTANT_URGENT);
        addDoubleClickEdit(notImportantNotUrgentArea, AppConstants.CATEGORY_NOT_IMPORTANT_NOT_URGENT);

        // 添加焦点监听器实现失焦保存
        addFocusListener(importantUrgentArea, AppConstants.CATEGORY_IMPORTANT_URGENT);
        addFocusListener(importantNotUrgentArea, AppConstants.CATEGORY_IMPORTANT_NOT_URGENT);
        addFocusListener(notImportantUrgentArea, AppConstants.CATEGORY_NOT_IMPORTANT_URGENT);
        addFocusListener(notImportantNotUrgentArea, AppConstants.CATEGORY_NOT_IMPORTANT_NOT_URGENT);
    }

    /**
     * 为文本区域添加双击编辑功能
     * @param textPane 文本区域
     * @param category 分类标识
     */
    private void addDoubleClickEdit(MarkdownEditorPane textPane, String category) {
        textPane.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getClickCount() >= 1) {
                    log.info("双击触发编辑 - 区域: {}", category);
                    enableEditing(textPane, category);
                }
            }
        });
    }

    /**
     * 添加焦点监听器，实现失去焦点时自动保存内容
     * @param textPane 文本区域
     * @param category 分类标识
     */
    private void addFocusListener(MarkdownEditorPane textPane, String category) {
        textPane.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                // 保存时移除末尾的空格
                String content = textPane.getText();

                // 转换Markdown内容为JSON格式再保存
                String jsonContent = dataAdapter.convertMarkdownToJson(content);
                scheduleManage.saveContent(category, jsonContent);
                textPane.setEditable(false);
            }
        });
    }

    /**
     * 添加窗口鼠标监听器，点击非文本区域时退出编辑模式
     */
    private void addWindowMouseListener() {
        Container contentPane = this.getContentPane();
        contentPane.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Component clickedComponent = SwingUtilities.getDeepestComponentAt(
                        contentPane, e.getX(), e.getY());

                if (!(clickedComponent instanceof MarkdownEditorPane)) {
                    log.info("点击非文本区域，退出编辑模式");
                    disableAllEditing();
                }
            }
        });
    }

    // ==================== 编辑相关方法 ====================

    /**
     * 启用文本区域的编辑模式
     * @param textPane 文本区域
     * @param category 分类标识
     */
    private void enableEditing(MarkdownEditorPane textPane, String category) {
        // 先禁用所有其他文本区域的编辑模式
        disableAllEditingExcept(textPane);

        // 启用当前文本区域编辑
        textPane.setEditable(true);
        textPane.requestFocusInWindow();
        textPane.getCaret().setVisible(true);

        log.info("已启用编辑模式 - 区域: {}", category);
    }

    /**
     * 禁用所有文本区域的编辑模式并保存内容
     */
    private void disableAllEditing() {
        disableAllEditingExcept(null);
    }

    /**
     * 禁用除指定文本区域外的所有文本区域编辑模式
     * @param except 需要排除的文本区域，不会被禁用
     */
    private void disableAllEditingExcept(MarkdownEditorPane except) {
        MarkdownEditorPane[] allAreas = {
                importantUrgentArea, importantNotUrgentArea,
                notImportantUrgentArea, notImportantNotUrgentArea
        };

        for (MarkdownEditorPane area : allAreas) {
            if (area != except && area.isEditable()) {
                String category = area.getCategory();
                // 转换Markdown内容为JSON格式再保存
                String jsonContent = dataAdapter.convertMarkdownToJson(area.getText());
                scheduleManage.saveContent(category, jsonContent);
                area.setEditable(false);
                area.getCaret().setVisible(false);
            }
        }
    }

    // ==================== 数据加载相关方法 ====================

    /**
     * 加载所有分类的内容到对应文本区域
     */
    private void loadAllContent() {
        String iuContent = scheduleManage.loadContent(AppConstants.CATEGORY_IMPORTANT_URGENT);
        importantUrgentArea.setText(dataAdapter.convertJsonToMarkdown(iuContent));

        String inuContent = scheduleManage.loadContent(AppConstants.CATEGORY_IMPORTANT_NOT_URGENT);
        importantNotUrgentArea.setText(dataAdapter.convertJsonToMarkdown(inuContent));

        String niuContent = scheduleManage.loadContent(AppConstants.CATEGORY_NOT_IMPORTANT_URGENT);
        notImportantUrgentArea.setText(dataAdapter.convertJsonToMarkdown(niuContent));

        String ninuContent = scheduleManage.loadContent(AppConstants.CATEGORY_NOT_IMPORTANT_NOT_URGENT);
        notImportantNotUrgentArea.setText(dataAdapter.convertJsonToMarkdown(ninuContent));
    }

    // ==================== 使命宣言 ====================
    /**
     * 显示使命宣言对话框
     */
    private void showMissionStatementDialog() {
        // 创建对话框
        JDialog dialog = new JDialog(this, AppConstants.MISSION_STATEMENT, true);
        dialog.setSize(160, 180);
        dialog.setLocationRelativeTo(this);

        // 创建文本区域
        JTextArea textArea = new JTextArea();
        textArea.setFont(AppConstants.DEFAULT_FONT);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        // 加载已保存的使命宣言内容
        String missionContent = loadMissionStatement();
        textArea.setText(missionContent);

        JScrollPane scrollPane = new JScrollPane(textArea);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        saveButton.addActionListener(e -> {
            saveMissionStatement(textArea.getText());
            dialog.dispose();
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        // 布局
        dialog.setLayout(new BorderLayout());
        dialog.add(scrollPane, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        dialog.setVisible(true);
    }

    /**
     * 保存使命宣言到本地文件
     * @param content 使命宣言内容
     */
    private void saveMissionStatement(String content) {
        try {
            scheduleManage.saveMissionStatement(content);
            JOptionPane.showMessageDialog(this, "使命宣言已保存", "提示", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException e) {
            log.error("保存使命宣言失败", e);
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 从本地文件加载使命宣言
     * @return 使命宣言内容
     */
    private String loadMissionStatement() {
        try {
            return scheduleManage.loadMissionStatement();
        } catch (IOException e) {
            log.error("加载使命宣言失败", e);
        }
        return "";
    }
}
